/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package view.GUI.actions;

import controller.BidirectionalHashMap;
import controller.Constants;
import controller.commands.AddAttachmentCommand;
import controller.commands.AddConnectionCommand;
import controller.commands.AddNodeCommand;
import controller.commands.DeleteCommand;
import java.awt.Point;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import load.ogp.Reference;
import model.graphic.GraphicModel;
import model.graphic.objects.GInputPort;
import model.graphic.objects.GOutput;
import model.graphic.objects.GOutputPort;
import model.graphic.objects.Graphical;
import load.parent.Function;
import view.GUI.graphic.GraphicView;
import view.GUI.listeners.DropListener;

/**
 *
 * @author Ben
 */
public class AddExpandedNodeAction extends AbstractAction{
    private GraphicView gview;
    private GOutput gOutPut;
    private GraphicModel gmodel;
    private Point point;

    public AddExpandedNodeAction(GraphicView gview,GraphicModel gmodel, GOutput gOutPut, Point point) {
        this.gview = gview;
        this.gOutPut = gOutPut;
        this.gmodel = gmodel;
        this.point = point;
    }

    public void actionPerformed(ActionEvent arg0) {
        Class c = null;
        if(AddAttachmentCommand.getClassFromPort((GOutputPort)gOutPut.getBase(), BidirectionalHashMap.getInstance())==Function.class){
            c = Function.class;
        }else{
            c = Reference.class;
        }
        AddNodeCommand anc = new AddNodeCommand(gmodel,gOutPut,c);
        anc.setLocation(DropListener.convertLocation(point, gview));
        gview.notifyObservers(anc);

        //search the GInputPort named "content"
        GInputPort input = null;
        java.util.ArrayList<Graphical> gs = gmodel.getAllObjects();
        int i = 0;
        while(i < gs.size() && input == null){
            if(gs.get(i).getClass().isAssignableFrom(GInputPort.class)
               && ((GInputPort)gs.get(i)).getName().equals("content")
               && ((GInputPort)gs.get(i)).getBase().equals(anc.getGNode())){
                    input = (GInputPort)gs.get(i);
            }
            i++;
        }
        
        //create a connection between the outport and the reference
        AddConnectionCommand adc = new AddConnectionCommand(gOutPut, input);
        gview.notifyObservers(adc);
        gview.notifyObservers(new DeleteCommand(gOutPut));
        gview.notifyObservers(new AddAttachmentCommand(Constants.getOutputString(),(GOutputPort) gOutPut.getBase()));
    }

}
